package com.nondo.rdp.auth.endpoint;


import com.nondo.rdp.auth.common.exception.enums.ParamExceptionEnums;
import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.auth.endpoint.model.RoleBean;
import com.nondo.rdp.auth.interceptor.OperationLog;
import com.nondo.rdp.auth.service.RoleService;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * com.seelyn.superp.core.endpoint
 *
 * @author linfeng
 * @since 2017/7/30
 */
@RestController
@RequestMapping("/api/sys/duties")
public class RoleEndpoint {

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    /**
     * 获取单个角色信息
     * @param id
     * @return
     */
    @RequestMapping("findOne/{id}")
    public View<Role> findOne(@PathVariable("id") Long id) {
        View<Role> view = View.ofOk();
        Role role;
        if (id != null) {
            role = roleService.findOne(id);
        } else {
            role = new Role();
        }
        view.setData(role);
        return view;
    }

    /**
     * 角色列表/搜索列表
     * @param query
     * @return
     */
    @RequestMapping(value = {"list", "search"})
    public View<Page<RoleBean>> search(@RequestBody Query<Role> query) {

        Role dict = query.getData();
        Page<Role> page = roleService.find(new Page<>(query.getPage(), query.getSize()), dict);
        Page<RoleBean> resultPage = page.convertPage(new ConvertCall<Role, Page<RoleBean>>() {

            @Override
            public Page<RoleBean> execute(Page<Role> srcPage) {
                Page<RoleBean> courseQueryPage = new Page<>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
                List<RoleBean> courseQueryList = new ArrayList<>();
                List<Role> courseBuyList = srcPage.getContent();
                for (Role role : courseBuyList) {
                    RoleBean courseQuery = RoleBean.covert2Bean(role);
                    courseQueryList.add(courseQuery);
                }
                courseQueryPage.setContent(courseQueryList);
                return courseQueryPage;
            }

        });

        View<Page<RoleBean>> view = View.ofOk();
        view.setData(resultPage);
        return view;

    }

    /**
     * 保存角色
     * @param roleBean
     * @param result
     * @param oldName
     * @return
     */
    @OperationLog
    @RequestMapping(value = "save")
    public View<String> save(@Validated @RequestBody RoleBean roleBean, BindingResult result, String oldName) {

        //表单校验
        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        }

        Role role = null;
        if (roleBean.getId() == null) {
            role = new Role();

            if (!"true".equals(checkName(oldName, roleBean.getName()))) {
                return View.ofError("保存角色'" + roleBean.getName() + "'失败, 角色名已存在");
            }

        } else {
            role = roleService.findOne(roleBean.getId());
        }
        BeanUtils.copy(roleBean, role);

        roleService.save(role);
        return View.ofOk("保存角色'" + role.getName() + "'成功");

    }

    /**
     * 检查角色名
     * @param oldName
     * @param name
     * @return
     */
    @RequestMapping(value = "checkName")
    public String checkName(@RequestParam String oldName, @RequestParam String name) {
        if (name != null && name.equals(oldName)) {
            return "true";
        } else if (name != null && roleService.findPositionByName(name) == null) {
            return "true";
        }
        return "false";
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @OperationLog
    @RequestMapping(value = "delete")
    public View<String> delete(@RequestParam Long id) {

        if (id != null) {
            roleService.delete(id);
        } else {
            return View.of(ParamExceptionEnums.PARAMS_NULL);
        }

        return View.ofOk("删除成功");
    }

    /**
     * 批量删除角色
     * @param ids
     * @return
     */
    @OperationLog
    @RequestMapping(value = "batchDelete")
    public View<String> batchDelete(@RequestParam Long[] ids) {

        if (ids == null) {
            return View.of(ParamExceptionEnums.PARAMS_NULL);
        }
        for (Long id : ids) {
            if (null != id) {
                roleService.delete(id);
            }
        }
        return View.ofOk();
    }

}